package day3.test;

import java.util.concurrent.locks.ReentrantLock;

public class Lock {
    public static void main(String[] args) {
        //创建两把锁的对象
        ReentrantLock lock1 = new ReentrantLock();
        ReentrantLock lock2 = new ReentrantLock();
        new Thread(
            ()->{
                while (true){
                    //锁嵌套
                    if (lock1.tryLock()){//如果进入if就说明得到1锁，否则在外死等，而且要保证释放1锁
                        try {
                            if (lock2.tryLock()){//获得2锁，只要进入if，就要保证释放2锁
                                try {
                                    System.out.println("先获取到了A, 再获取到B锁, 开搞!");
                                }finally {
                                    lock2.unlock();//释放2锁
                                }
                            }
                        }finally {
                            lock1.unlock();//释放1锁
                        }
                    }
                }
            }).start();
        new Thread(
                ()->{
                    while (true){
                        if (lock2.tryLock()){
                            try {
                                if (lock1.tryLock()){
                                    try {
                                        System.out.println("先获取到了B, 再获取到A锁, 开干!!!");
                                    }finally {
                                        lock1.unlock();
                                    }
                                }
                            }finally {
                                lock2.unlock();
                            }
                        }
                    }
                }).start();
        }
    }

